package com.zjr.common.core.domain;

import lombok.Data;
import com.zjr.common.core.enums.ResultCode;

/**
 * 通用的返回形式
 * @param <T>
 */
@Data
public class R<T> {
    private int code;
    private String msg;
    private T data;
    public static <T>R<T> ok(T data){
        return assembleResult(data, ResultCode.SUCCESS);
    }

    public static <T>R<T> ok(){
        return assembleResult(null, ResultCode.SUCCESS);
    }

    /**
     * 返回通用错误码
     * @return
     * @param <T>
     */
    public static <T>R<T> fail(){
        return assembleResult(null, ResultCode.FAILED);
    }

    public static <T>R<T> fail(int code, String msg){
        return assembleResult(code,  msg, null);
    }
    /**
     * 指定错误码
     * @param code
     * @return
     * @param <T>
     */
    public static <T>R<T> fail(ResultCode code){
        return assembleResult(null, code);
    }

    public static <T>R<T> assembleResult(T data, ResultCode code){
        R<T> r = new R<>();
        r.setData(data);
        r.setMsg(code.getMsg());
        r.setCode(code.getCode());
        return r;
    }
    public static <T>R<T> assembleResult(int code, String msg, T data){
        R<T> r = new R<>();
        r.setData(data);
        r.setMsg(msg);
        r.setCode(code);
        return r;
    }
}
